package org.jeecg.modules.simulator.factory.train.plan;

import org.jeecg.modules.simulator.model.line.plan.TrainPlanTablePath;
import org.jeecg.modules.simulator.model.train.action.*;
import org.jeecg.modules.simulator.model.train.timeplan.PlanTableItem;
import org.jeecg.modules.simulator.util.SimulatorParamStr;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: 列车时刻表转换成列车动作记录表
 * @description:
 * @author: lydms
 * @create: 2024-08-08 10:05
 **/
public class TrainActionRDSFactory {

    private static final Logger logger = LoggerFactory.getLogger(TrainActionRDSFactory.class);

    /**
     * @description: 创建列车动作记录表
     * @author: renzhg
     * @date: 2024/9/19 10:04
     **/
    public static Map<String, TrainActionRecorders> createTrainActionRecorders(
            Map<String, TrainPlanTablePath> trainPlanTablePathMap, String lineId
    ) {
        Map<String, TrainActionRecorders> trainActionRecordersMap = new LinkedHashMap<>();
        for (String key : trainPlanTablePathMap.keySet()) {
            TrainPlanTablePath trainPlanTables = trainPlanTablePathMap.get(key);
            if (trainPlanTables != null) {
                TrainActionRecorders trainActionRecorders = initializeTrainActionRecorders(key);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
                LocalTime localTime = LocalTime.parse(trainPlanTables.getFirstTime(), formatter);
                trainActionRecorders.setFistActionTime(localTime);
                trainActionRecorders.setLineId(lineId);
                Map<Integer, TrainActionRecorder> trainActionRecorderMap = createTrainActionRecorderMap(trainPlanTables);
                TrainActionRecorder lastRecorder = trainActionRecorderMap.get(trainActionRecorderMap.size());
                if (lastRecorder != null) {
                    lastRecorder.setLast(true);
                }
                trainActionRecorders.setTrainActionRecordMap(trainActionRecorderMap);
                trainActionRecorders.setStatus(ActionRecordersStatus.nostart);
                trainActionRecorders.setTrainActionRecordersType(SimulatorParamStr.ACTION_RECORDERS_TYPE_NORMAL);
                trainActionRecordersMap.put(key, trainActionRecorders);
            }


        }

        return trainActionRecordersMap;


//        Map<String, TrainActionRecorders> trainActionRecordersMap = new LinkedHashMap<>();
//
//        for (String key : trainPlanTablePathMap.keySet()) {
//
//            TrainPlanTablePath trainPlanTables = trainPlanTablePathMap.get(key);
//            if (trainPlanTables != null) {
//                TrainActionRecorders trainActionRecorders = new TrainActions();
//                trainActionRecorders.setRocordersId(key);
//                Map<Integer, TrainActionRecorder> trainActionRecorderMap = new LinkedHashMap<>();
//                Map<Integer, PlanTableItem> planTableItemMap = trainPlanTables.getPlanTableItemMap();
//
//                int count = 1;
//
//                for (Map.Entry<Integer, PlanTableItem> planTableItemEntrylanTableItem : planTableItemMap.entrySet()) {
//                    PlanTableItem planTableItem = planTableItemEntrylanTableItem.getValue();
//                    if (planTableItem.getType().equals("sect")) {
//                        addTrainRuningActionRecorder(trainActionRecorderMap, count, planTableItem, ACTION_RUN);
//                    } else {
//                        addTrainNoRuningActionRecorder(trainActionRecorderMap, count, planTableItem, ACTION_STOP);
//                    }
//                    count++;
//                }
//                TrainActionRecorder trainActionRecorder = trainActionRecorderMap.get(count-1);
//                trainActionRecorder.setLast(true);
//
//                trainActionRecorders.setTrainActionRecordMap(trainActionRecorderMap);
//
//                trainActionRecorders.setStatus(ActionRecordersStatus.nostart);
//                trainActionRecordersMap.put(key, trainActionRecorders);
//            }
//
//        }
//
//        return trainActionRecordersMap;
    }


    /**
     * @description: 新建一个列车动作记录器
     * @author: renzhg
     * @date: 2024/9/19 9:27
     **/
    private static TrainActionRecorders initializeTrainActionRecorders(String key) {
        TrainActionRecorders trainActionRecorders = new TrainActions();
        trainActionRecorders.setRocordersId(key);
        return trainActionRecorders;
    }

    /**
     * @description: 分解列车时刻表，生成列车动作记录器
     * @author: renzhg
     * @date: 2024/9/19 9:28
     **/
    private static Map<Integer, TrainActionRecorder> createTrainActionRecorderMap(TrainPlanTablePath trainPlanTables) {
        Map<Integer, TrainActionRecorder> trainActionRecorderMap = new LinkedHashMap<>();
        Map<Integer, PlanTableItem> planTableItemMap = trainPlanTables.getPlanTableItemMap();

        int count = 1;
        String lastActionName = "";
        for (Map.Entry<Integer, PlanTableItem> entry : planTableItemMap.entrySet()) {
            PlanTableItem planTableItem = entry.getValue();


            if (planTableItem.getType().equals(SimulatorParamStr.TYPE_SECT)) {
                lastActionName = planTableItem.getName();
                addTrainRuningActionRecorder(trainActionRecorderMap, count, planTableItem, SimulatorParamStr.ACTION_RUN);
            } else {
                if(!lastActionName.isEmpty()){
                    addTrainNoRuningActionRecorder(trainActionRecorderMap, count, planTableItem, SimulatorParamStr.ACTION_STOP,lastActionName);
                }else{
                    addTrainNoRuningActionRecorder(trainActionRecorderMap, count, planTableItem, SimulatorParamStr.ACTION_STOP,planTableItem.getName());
                }

            }
            count++;
        }
        return trainActionRecorderMap;
    }

    /**
     * @description: 生产添加动作
     * @author: renzhg
     * @date: 2024/8/6 16:21
     **/
    private static void addTrainNoRuningActionRecorder(Map<Integer, TrainActionRecorder> recorderMap,
                                                       Integer index,

                                                       PlanTableItem planTableItem,
                                                       String action,String lastActionName) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        TrainActionRecorder trainActionRecorder = new TrainAction(planTableItem.getName(), action);
        trainActionRecorder.setAffiliateType(SimulatorParamStr.ACTION_DOCKING);
        trainActionRecorder.setLast(false);
        trainActionRecorder.setTableItemId(planTableItem.getVid());
        trainActionRecorder.setTableItemName(lastActionName);
//        trainActionRecorder.setPlanSpeed(0);

        try {
            // 使用 LocalDateTime.parse() 进行解析
            trainActionRecorder.setStartTime(LocalTime.parse(planTableItem.getArrivalTime(), formatter));
            trainActionRecorder.setEndTime(LocalTime.parse(planTableItem.getDepartureTime(), formatter));
            trainActionRecorder.setExecutionStatus(ExecutionStatus.initialize);

        } catch (DateTimeParseException e) {
            e.printStackTrace();
            logger.debug("Invalid date-time format: " + e.getMessage());
        }

        recorderMap.put(index, trainActionRecorder);
    }


    private static void addTrainRuningActionRecorder(Map<Integer, TrainActionRecorder> recorderMap,
                                                     Integer index,
                                                     PlanTableItem planTableItem,
                                                     String action) {
        TrainActionRecorder trainActionRecorder = new TrainAction(planTableItem.getName(), action);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        try {
            trainActionRecorder.setStartTime(LocalTime.parse(planTableItem.getArrivalTime(), formatter));
            trainActionRecorder.setEndTime(LocalTime.parse(planTableItem.getDepartureTime(), formatter));
            trainActionRecorder.setExecutionStatus(ExecutionStatus.initialize);
            trainActionRecorder.setAffiliateType(SimulatorParamStr.ACTION_RUN);
            trainActionRecorder.setLast(false);
            trainActionRecorder.setTableItemId(planTableItem.getVid());
            trainActionRecorder.setTableItemName(planTableItem.getName());
        } catch (DateTimeParseException e) {
            e.printStackTrace();
            logger.info("Invalid date-time format: " + e.getMessage());
        }
        recorderMap.put(index, trainActionRecorder);
    }


    /**
     * @description: 装配轨道
     * @author: renzhg
     * @date: 2024/8/8 10:18
     * @param:
     * @return:
     * @return: java.util.Map<java.lang.String, com.renzhg.gp.gp.simulator.model.MetroTrain>
     **/
//    public Map<String,MetroTrain> awareOrbitPath(Map<String, Map<String, OrbitPoint>> orbitPaths, Map<String, TrainPhysics>  trainPhysicsMap ){
////        Map<String, Map<String, OrbitPoint>> orbitPaths = orbitPathFileDataLoader.getOrbitPaths();
////        Map<String, MetroTrain> metroTrainMap = createMetroTrain(orbitPaths,trainPhysicsMap);
////        return  Collections.synchronizedMap(metroTrainMap);
//    }

/**
 * @description: 装配时刻表变动作记录表
 * @author: renzhg
 * @date: 2024/8/8 10:21
 * @param:
 * @return:
 * @return: java.util.Map<java.lang.String, com.renzhg.gp.gp.simulator.model.train.action.TrainActionRecorders>
 **/
//    public Map<String, TrainActionRecorders> createTrain(){
//
//        Map<String, TrainPlanTablePath> trainPlanTablePathMap = trainPlanTableLoader.getTrainPlanTablePathMap();
//        Map<String, TrainActionRecorders> trainActionRecorders = TrainActionRDSFactory.createTrainActionRecorders(trainPlanTablePathMap);
//        return trainActionRecorders;
//    }

//    public Map<String,MetroTrain> createMetroTrain(Map<String, Map<String, OrbitPoint>> orbitPaths,
//                                                   Map<String, TrainPhysics> trainPhysicsMap,
//                                                   Map<String, List<String>> lineTrainMap
//    ) {
////        Map<String, List<String>> lineTrainMap = lineTrainLoader.getLineTrainMap();
//
//        lineTrainMap.forEach((k, v) -> {
//            for (int i = 0; i < v.size(); i++) {
//                MetroTrain metroTrain = new MetroTrain();
//                String trainid = v.get(i).split("-")[0];
//                String trainNo = v.get(i).split("-")[1];
//                Map<String, OrbitPoint> orbitPointMap = orbitPaths.get(k);
//                //装配轨道
//                TrainBiz trainBiz = new TrainBiz(orbitPointMap);
//                trainBiz.setLastState(TrainRunState.start);
//                metroTrain.setTrainPhysics(trainFileDataLoader.getTrainPhysicsMap().get(trainid));
//                TrainPhysics trainPhysics=new TrainPhysics();
//                trainPhysics=trainPhysicsMap.get("s1");
//                metroTrain.setTrainPhysics(trainPhysics);
//
//                metroTrain.setTrainId(trainid);
//                metroTrain.setTrainNum(trainNo);
//                metroTrain.setTrainBiz(trainBiz);
//
//                metroTrainMap.put(v.get(i), metroTrain);
//            }
////            MetroTrain metroTrain = new MetroTrain();
////            metroTrainMap.put(k, metroTrain);
//        });
//        return metroTrainMap;
//    }
}
